<html>

<head>
<title>Calculator</title>
</head>

<body>

<h1>Calculator</h1>

<p>
<form method="GET">
<input type="text" name="exp"><input type="submit" value="Calculate">
</form>
</p>

<h2>Result</h2>

<?php

ini_set("display_errors", "Off");

$mathExp = preg_replace( '#\s+#', ' ', $_GET["exp"] );

// $mathExp = preg_replace( '#[^1-9/.]0+#', '0', $mathExp );

// Check two consecutive numbers are not connected with operator
if( preg_match( "#[0-9]( )[0-9]#", $mathExp ))
  echo "Invalid input expression: " . $mathExp . "  (numbers are not connected with an operator)";

// Check characters other than digits and + - * / operators
else if( preg_match( "#[^0-9\+\-\*\/ \.]#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . "  (charaters other than digits and +, -, *, /)";

// Check devided by 0
else if( preg_match( "#\/( )*[0]{1, }#", $mathExp ) ) 
// || preg_match( "#\/( )*0+\.0+[^1-9]#", $mathExp) )
  echo "Invalid input expression: " . $mathExp . " -- divided by 0.";

// Check three consecutive operators
else if( preg_match( "#[\+\-\*\/]( )*[\+\-\*\/]( )*[\+\-\*\/]#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . "  (3 consecutive operators)";

// Check two consecutive operators like '[+|-|*|/] [*|/]'
else if( preg_match( "#[\+\-\*\/]( )*[\*\/]#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . "  (+|-|*|/ followed by *|/)" ;

// Check operators like '++' or '--' (no space between operators)
else if( preg_match( "#(\+\+|\-\-)#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . " ++ or -- .";

// Check ending with an operator
else if( preg_match( "#[\+\-\*\/]$#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . "  (ending with an operator)";

// Check beginning with * or /
else if( preg_match( "#^[\*\/]#", $mathExp ) )
  echo "Invalid input expression: " . $mathExp . "  (beginning with *|/)";

// Output result if the expression is not empty
else if( $mathExp != "" || $mathExp != " " )
  echo $mathExp . " = " . eval( "return " . $mathExp . ";" ) ;

?>

</body>

</html>
